package com.core.website.service.impl;

import com.core.website.common.Result;
import com.core.website.common.ResultUtil;
import com.core.website.entity.CoreFile;
import com.core.website.mapper.FileMapper;
import com.core.website.service.FileService;
import com.core.website.util.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private FileMapper fileMapper;
    @Resource
    private FileUtil fileUtil;



    @Override
    public Result uploadFiles(List<MultipartFile> files) {
        List<Map<String, Object>> fileIds = new ArrayList<>();

        for (MultipartFile file : files) {
            String replace = UUID.randomUUID().toString().toUpperCase().replace("-", "");
            String fileName = file.getOriginalFilename();

            int begin = file.getOriginalFilename().indexOf(".");
            int last = file.getOriginalFilename().length();
            String fileType = file.getOriginalFilename().substring(begin, last);
            String fileAddress = null;
            try {
                fileAddress = fileUtil.upload(file);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error(7777, "文件上传失败，请重试");
            }
            CoreFile breedFile = new CoreFile();
            breedFile.setId(replace);
            breedFile.setName(fileName);
//            catFile.setFileSize(fileSize);
            breedFile.setType(fileType);
            breedFile.setAddress(fileAddress);
            fileMapper.addFile(breedFile);
            Map<String, Object> m = new HashMap();
            m.put("id", breedFile.getId());
            m.put("name", fileName);
            m.put("address",fileAddress);
            fileIds.add(m);
        }
        return ResultUtil.success(fileIds);
//        return fileIds;
    }

    @Override
    public Object getVisitUrl(String fileId) {
        //TODO 后期要加上redis缓存，避免频繁请求同一资源？？？
        CoreFile breedFile = fileMapper.getById(fileId);
        if (breedFile == null) {
            return "无此文件";
        }
        return breedFile.getAddress();
    }

}
